package cn.wolfcode.edu.web.controller;

import cn.wolfcode.edu.domain.ClassGrade;
import cn.wolfcode.edu.domain.Classroom;
import cn.wolfcode.edu.domain.Employee;
import cn.wolfcode.edu.domain.Schedule;
import cn.wolfcode.edu.query.ScheduleQueryObject;
import cn.wolfcode.edu.service.IClassGradeService;
import cn.wolfcode.edu.service.IClassroomService;
import cn.wolfcode.edu.service.IEmployeeService;
import cn.wolfcode.edu.service.IScheduleService;
import cn.wolfcode.edu.util.JsonResult;
import cn.wolfcode.edu.util.PageResult;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by ASUS on 2018/7/10.
 */
@Controller
@RequestMapping("schedule")
public class ScheduleController {


    @Autowired
    private IScheduleService scheduleService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IClassGradeService classGradeService;
    @Autowired
    private IClassroomService classroomService;

    //主页定位
    @RequestMapping("")
    public String index(){
        return "schedule";
    }
    //查询所有课表
    @RequestMapping("list")
    @ResponseBody
    public PageResult list(ScheduleQueryObject qo){
        return scheduleService.query(qo);
    }
    //保存课表
    @RequestMapping("save")
    @ResponseBody
    public JsonResult saveSchedule(Schedule schedule){
        JsonResult jsonResult = new JsonResult();
        try{
            scheduleService.saveSchedule(schedule);
        }catch(Exception e){
            e.printStackTrace();
            jsonResult.setMsg("保存失败啦呀.....");
        }
        return jsonResult;
    }
    //编辑课表
    @RequestMapping("update")
    @ResponseBody
    public JsonResult updateSchedule(Schedule schedule){
        JsonResult jsonResult = new JsonResult();
        try{
            scheduleService.updateSchedule(schedule);
        }catch(Exception e){
            e.printStackTrace();
            jsonResult.setMsg("编辑失败啦呀.....");
        }
        return jsonResult;
    }
    //删除课表
    @RequestMapping("delete")
    @ResponseBody
    public JsonResult deleteSchedule(Long id){
        JsonResult jsonResult = new JsonResult();
        try{
            scheduleService.deleteSchedule(id);
        }catch(Exception e){
            e.printStackTrace();
            jsonResult.setMsg("删除失败.....");
        }
        return jsonResult;
    }
    //文件导出方法
    @RequestMapping("export")
    @ResponseBody
    public void export(ScheduleQueryObject qo, HttpServletResponse resp) throws Exception {
        qo.setRows(2000);
        List<Schedule> list = scheduleService.queryForList(qo);
        SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM-dd");
        resp.setHeader("Content-Disposition", "attachment;filename=schedule.xls");
        ServletOutputStream outputStream = resp.getOutputStream();
        //创建一个工作簿
        WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
        //创建sheet
        WritableSheet sheet = workbook.createSheet("schedule", 0);
        Label subject = new Label(0, 0, "学科名");
        Label subDate = new Label(1, 0, "课程日期");
        Label remark = new Label(2, 0, "备注");
        Label classgrade = new Label(3, 0, "上课班级");
        Label teacher = new Label(4, 0, "上课教师");
        Label classroom = new Label(5, 0, "上课教室");
        Label coordinator = new Label(6, 0, "班主任");
        sheet.addCell(subject);
        sheet.addCell(subDate);
        sheet.addCell(remark);
        sheet.addCell(classgrade);
        sheet.addCell(teacher);
        sheet.addCell(classroom);
        sheet.addCell(coordinator);
        for (int i = 0; i < list.size(); i++) {
            Schedule e = (Schedule) list.get(i);
            int row = i + 1;
            Label subjectCon = new Label(0, row, e.getSubject());
            Label subDateCon = new Label(1, row, sdfMonth.format(e.getSubDate()));
            Label remarkCon = new Label(2, row, e.getRemark());
            Label classgradeCon = new Label(3, row, e.getClassgrade().getName());
            Label teacherCon = new Label(4, row, e.getTeacher().getRealName());
            Label classroomCon = new Label(5, row, e.getClassroom().getName());
            Employee coordinator1 = e.getCoordinator();
            Label coordinatorCon = new Label(6, row,coordinator1!=null? coordinator1.getRealName(): "");
            sheet.addCell(subjectCon);
            sheet.addCell(subDateCon);
            sheet.addCell(remarkCon);
            sheet.addCell(classgradeCon);
            sheet.addCell(teacherCon);
            sheet.addCell(classroomCon);
            sheet.addCell(coordinatorCon);
        }
        workbook.write();
        workbook.close();
    }
    @RequestMapping("download")
    @ResponseBody
    public void download(HttpServletResponse response, Long id, HttpSession session) throws Exception {
        String fileName = new String("学科表模板".getBytes("utf-8"), "ISO-8859-1");
        response.setHeader("Content-Disposition", (new StringBuilder()).
                append("attachment;filename=").append(fileName).append(".xls").toString());
        WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
        WritableSheet sheet = workBook.createSheet("学科表模板", 0);

        sheet.addCell(new Label(0, 0, "学科名"));
        sheet.addCell(new Label(1, 0, "课程日期"));
        sheet.addCell(new Label(2, 0, "备注"));
        sheet.addCell(new Label(3, 0, "上课班级"));
        sheet.addCell(new Label(4, 0, "上课教师"));
        sheet.addCell(new Label(5, 0, "上课教室"));
        sheet.addCell(new Label(6, 0, "班主任"));
        workBook.write();
        workBook.close();
    }
    @RequestMapping("importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) {
        JsonResult jsonResult = new JsonResult();
        try {
            Workbook workBook = null;
            workBook = Workbook.getWorkbook(file.getInputStream());
            Sheet sheet = workBook.getSheet(0);
            int rows = sheet.getRows();
            //设置时间的格式
            SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfPayTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 1; i < rows; i++) {
                Schedule  schedule = new Schedule();
                String contents = sheet.getCell(0, i).getContents();
                schedule.setSubject(contents);
                contents =sheet.getCell(1, i).getContents();
                schedule.setSubDate(sdfMonth.parse(contents));
                contents =sheet.getCell(2, i).getContents();
                schedule.setRemark(contents);
                contents =sheet.getCell(3, i).getContents();
                Long ClassGradeId = classGradeService.getIdByName(contents);
                ClassGrade classGrade = new ClassGrade();
                classGrade.setId(ClassGradeId);
                schedule.setClassgrade(classGrade);
                contents =sheet.getCell(4, i).getContents();
                Employee employee = employeeService.selectByRealName(contents);
                schedule.setTeacher(employee);
                contents =sheet.getCell(5, i).getContents();
                Classroom classroom = classroomService.getByName(contents);
                schedule.setClassroom(classroom);
                contents =sheet.getCell(6, i).getContents();
                Employee employee1 = employeeService.selectByRealName(contents);
                schedule.setCoordinator(employee1);
                scheduleService.saveSchedule(schedule);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.remark("导入失败!");
        }
        return jsonResult;
    }
}
